const express = require('express');
const router = express.Router();
const { User } = require('../database/models');
const { 
  generateToken,
  authenticate,
  asyncHandler 
} = require('../middleware');
const { 
  validate,
  loginValidation,
  registerValidation 
} = require('../middleware/validation');

// 用户注册
router.post('/register', 
  validate(registerValidation),
  asyncHandler(async (req, res) => {
    const { name, phone, password, role, email, address } = req.body;

    // 检查用户是否已存在
    const existingUser = await User.findOne({ phone });
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '该手机号已注册',
        code: 400,
        data: null
      });
    }

    // 创建新用户
    const user = new User({
      name,
      phone,
      password,
      role: role || 'user',
      email,
      address
    });

    await user.save();

    // 生成token
    const token = generateToken(user._id);

    res.status(201).json({
      success: true,
      message: '注册成功',
      code: 201,
      data: {
        id: user._id,
        name: user.name,
        phone: user.phone,
        role: user.role,
        email: user.email,
        address: user.address,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      }
    }).header('Authorization', `Bearer ${token}`);
  })
);

// 用户登录
router.post('/login', 
  validate(loginValidation),
  asyncHandler(async (req, res) => {
    const { phone, password } = req.body;

    // 查找用户（包含密码字段）
    const user = await User.findOne({ phone }).select('+password');
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '手机号或密码错误',
        code: 401,
        data: null
      });
    }

    // 检查账户是否激活
    if (!user.isActive) {
      return res.status(401).json({
        success: false,
        message: '账户已被禁用，请联系管理员',
        code: 401,
        data: null
      });
    }

    // 验证密码
    const isPasswordValid = await user.comparePassword(password);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '手机号或密码错误',
        code: 401,
        data: null
      });
    }

    // 更新最后登录时间
    user.lastLoginAt = new Date();
    await user.save();

    // 生成token
    const token = generateToken(user._id);

    // 设置Authorization头部
    res.header('Authorization', `Bearer ${token}`);
    
    // 发送JSON响应
    res.status(200).json({
      success: true,
      message: '登录成功',
      code: 200,
      data: {
        id: user._id,
        name: user.name,
        phone: user.phone,
        role: user.role,
        email: user.email,
        address: user.address,
        avatar: user.avatar,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        lastLoginAt: user.lastLoginAt,
        token: token  // 在响应数据中包含token
      }
    });
  })
);

// 获取当前用户信息
router.get('/me', 
  authenticate,
  asyncHandler(async (req, res) => {
    const user = req.user;

    res.status(200).json({
      success: true,
      message: '获取用户信息成功',
      code: 200,
      data: {
        id: user._id,
        name: user.name,
        phone: user.phone,
        role: user.role,
        email: user.email,
        address: user.address,
        avatar: user.avatar,
        specialties: user.specialties,
        experience: user.experience,
        rating: user.rating,
        completedOrders: user.completedOrders,
        isActive: user.isActive,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        lastLoginAt: user.lastLoginAt
      }
    });
  })
);

// 更新用户信息
router.put('/profile', 
  authenticate,
  asyncHandler(async (req, res) => {
    const userId = req.user._id;
    const updates = req.body;

    // 不允许更新的字段
    const forbiddenFields = ['password', 'role', 'phone', 'isActive', 'completedOrders', 'rating'];
    forbiddenFields.forEach(field => {
      if (updates[field] !== undefined) {
        delete updates[field];
      }
    });

    const user = await User.findByIdAndUpdate(
      userId,
      { $set: updates },
      { new: true, runValidators: true }
    );

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    res.status(200).json({
      success: true,
      message: '用户信息更新成功',
      code: 200,
      data: {
        id: user._id,
        name: user.name,
        phone: user.phone,
        role: user.role,
        email: user.email,
        address: user.address,
        avatar: user.avatar,
        specialties: user.specialties,
        experience: user.experience,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      }
    });
  })
);

// 修改密码
router.put('/password', 
  authenticate,
  asyncHandler(async (req, res) => {
    const { currentPassword, newPassword } = req.body;

    if (!currentPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '当前密码和新密码都不能为空',
        code: 400,
        data: null
      });
    }

    if (newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码至少需要6个字符',
        code: 400,
        data: null
      });
    }

    // 查找用户（包含密码字段）
    const user = await User.findById(req.user._id).select('+password');
    
    // 验证当前密码
    const isCurrentPasswordValid = await user.comparePassword(currentPassword);
    if (!isCurrentPasswordValid) {
      return res.status(400).json({
        success: false,
        message: '当前密码错误',
        code: 400,
        data: null
      });
    }

    // 更新密码
    user.password = newPassword;
    await user.save();

    res.status(200).json({
      success: true,
      message: '密码修改成功',
      code: 200,
      data: null
    });
  })
);

// 登出（客户端处理token删除）
router.post('/logout', 
  authenticate,
  asyncHandler(async (req, res) => {
    res.status(200).json({
      success: true,
      message: '登出成功',
      code: 200,
      data: null
    });
  })
);

module.exports = router;